<template>
	<view class="content" :class="[successShow?'no-scroll':'']">
		<u-popup :show="successShow"  mode="center" :round="75">
			<view style="height: 300rpx;width: 300rpx;text-align: center;">
				<view style="margin-top: 25%;">
					<image src="https://jiaoguanyi008.oss-cn-shenzhen.aliyuncs.com/miniPro/images/imgs/check.png" mode="widthFix" style="width: 140rpx;"></image>
					<view class="">提交成功</view>
				</view>
					<!-- <text>出淤泥而不染，濯清涟而不妖</text> -->
			</view>
		</u-popup>
		<u-toast ref="uToast"></u-toast>
		<u-modal :show="show" title="温馨提示" content='您还未将售后包裹寄出，请寄出后填写快递单号后再进行提交~' @confirm="confirm"></u-modal>
		<!-- 时间选择器 -->
		<u-datetime-picker :show="dateShow" v-model="value" mode="datetime" @confirm="dateConfirm"
			@cancel="dateShow = false" closeOnClickOverlay @close="dateShow = false"></u-datetime-picker>
		<view class="client_type box_redius " :class="[current==0?'blueBg':'']">
			<view class="flex flex_align">
				<view class="header_star" style="margin-right: 40rpx;width: 240rpx;"><text class="iconfont icon-vip"
						style="font-size: 40rpx"></text>客户类型
						<!-- <text class="five_star iconfont icon-shiwujiaoxing"></text> -->
				</view>
				<view class="type">
					<u-subsection 
					:list="list" 
					:current="current" 
					mode="button" 
					@change="changeSubsection"
					bgColor="#f4f4f4"
					inactiveColor="#898989"
					activeColor="#fff">
					</u-subsection>
				</view>
			</view>
			<!-- v-show="afterSale.customer_type === 2" -->
			<!-- 省市选择 -->
			<view class="city_selcet mar_top" v-show="afterSale.customer_type === 2">
				<view class="flex flex_align flex_bet">
					<view class="city_input flex flex_align"><text class="mar_right" style="color:#2785ff;">省</text>
						<view class="" style="width: 100%">
							<uni-data-select v-model="afterSale.user_province" :localdata="province"
								@change="provinceChange($event, 'city')">
							</uni-data-select>
						</view>
					</view>
					<view class="city_input flex flex_align"><text class="mar_right" style="color:#2785ff;">市</text>
						<view class="" style="width: 100%">
							<uni-data-select v-model="afterSale.user_city" :localdata="city"
								@change="provinceChange($event, 'county')"></uni-data-select>
						</view>
					</view>
				</view>
				<view class="flex flex_align flex_bet mar_top">
					<view class="city_input flex flex_align"><text class="mar_right" style="color:#2785ff;">县</text>
						<view class="" style="width: 100%">
							<uni-data-select v-model="afterSale.user_county" :localdata="county"
								@change="provinceChange($event, 'region')"></uni-data-select>
						</view>
					</view>
					<view class="city_input flex flex_align"><text class="mar_right" style="color:#2785ff;">区</text>
						<view class="" style="width: 100%">
							<uni-data-select v-model="afterSale.user_area" :localdata="region"></uni-data-select>
						</view>
					</view>
				</view>
			</view>
		</view>

		<Mail>
			<view class="client_type mar_top flex flex_align mar_bottom" slot="mailDate">
				<view class="header_star dateTime">预约上门取件时间:</view>
				<view class="model mar_left address_info" @click.stop="dateShow = true">
					<u-input v-model="dateValue" :fontSize="12" placeholder="请选择取件时间"
						border="surround" suffixIcon="arrow-down" disabled>
					</u-input>
				</view>
			</view>
			<view class="client_type mar_top flex flex_align" slot="mailNumber">
				<view class="header_star" style="width: 200rpx;color: #de6e67;font-weight: 700;">快 递 单 号：</view>
				<u--input v-model="afterSale.express_number" 
				placeholder="请输入快递单号" 
				border="bottom" 
				placeholder-style="color:#de6e67"
				:custom-style="{background:'#f1f2f4', height:'50rpx',lineHeight:'50rpx',border:'none',borderRadius:'10rpx',}" 
				clearable>
				</u--input>
				<view class="camera iconfont icon-xiangji" @click="uploadImg" style="z-index: 2;"></view>
				
			<!-- 	<view class="header_star" style="width: 180rpx;">快 递 单 号：</view>
				<u--input v-model="afterSale.express_number" placeholder="若未寄出,可先点暂存" border="bottom" clearable>
				</u--input>
				<view class="camera iconfont icon-xiangji" @click="uploadImg"></view> -->
			</view>
		</Mail>

		<view class="client_type  mar_top">
			<model-number ref="modelN" :checkboxList="checkboxList" :productList="productList" :faultList="faultList">
			</model-number>
		</view>

		

		<view class="footer_client_type  mar_top excel flex flex_align flex_bet">
			<view class="box box_redius" @click="addProduct"><text class="iconfont icon-zengjia1"></text>添加产品</view>
			<view class="box box_redius" @click="getExcel"><text class="iconfont icon-piliangdaoru"></text>批量导入excel</view>
		</view>

		<u-button text="提交" :type="afterSale.express_number.trim() ? 'primary' : 'primary'" shape="circle" @click="submitConfirm" throttleTime="3000" customStyle="width:70%;margin-top:20rpx;"></u-button>
		
			<!-- <view class="client_type box_redius mar_top excel flex flex_align flex_bet">
				<view class="box flex flex_align flex_cen" @click="addProduct"><text
						class="add_icon iconfont icon-zengjia1"></text>添加产品</view>
				<view class="line"></view>
				<view class="box" @click="getExcel"><text class="iconfont icon-piliangdaoru"></text>批量导入excel</view>
			</view> -->
			
		<!-- <view class="mar_top mar_bottom flex flex_align flex_bet">
			<view class="btn">
				<u-button text="暂存" :type="afterSale.express_number.trim() ? '' : 'primary'" @click="show = true"
					throttleTime="3000"></u-button>
			</view>
			<view class="btn">
				<u-button text="提交" :type="afterSale.express_number.trim() ? 'primary' : ''" @click="submitConfirm"
					throttleTime="3000"></u-button>
			</view>
		</view> -->

		<!-- <view class="client_type box_redius mar_top">
			<view class="header_star">寄回地址<text class="five_star iconfont icon-shiwujiaoxing"></text></view>
			<view class="flex flex_align flex_bet">
				<view class="address_info">
					<view class="font_w title">{{address.firm.name}} {{address.firm.phone}}</view>
					<view>{{address.firm.addr}}</view>
				</view>
				<view class="address_icon" @click="goToUrl('/pages/afterAddress/index')"><text
						class="iconfont icon-dizhibu"></text>
					<view>地址簿</view>
				</view>
			</view>
		</view>

		<view class="client_type box_redius mar_top">
			<view class="header_star">寄出地址<text class="five_star iconfont icon-shiwujiaoxing"></text></view>
			<view class="flex flex_align flex_bet">
				<view class="address_info">
					<view class="font_w title">{{address.person.name}} {{address.person.phone}}</view>
					<view>{{address.person.addr}}</view>
				</view>
				<view class="address_icon" @click="goToUrl('/pages/myAddress/index')"><text
						class="iconfont icon-dizhibu"></text>
					<view>地址簿</view>
				</view>
			</view>
		</view> -->
	</view>
</template>

<script>
	import modelNumber from './component/modeleNumber.vue'
	import Mail from './component/mail.vue'
	import QQMapWX from '@/utils/qqmap-wx-jssdk.js'
	import {
		repairAdd
	} from '@/api/repair.js'
	import {
		productList,
		productmodelList,
		faultList
	} from '@/api/product.js'
	import {
		mapState
	} from 'vuex'
	import {
		dateNew
	} from '@/utils/index.js'
	export default {
		components: {
			modelNumber,
			Mail
		},
		computed: {
			...mapState([
				'afterSale',
				'address'
			]),
			//预约上门格式化时间
			dateValue(){
				if(!this.afterSale.pickup_start_time) return ''
				let date = new Date(parseInt(this.value));
				let y = date.getFullYear();
				let m = (date.getMonth() + 1 + '').padStart(2, '');
				let d = (date.getDate() + '').padStart(2, '0');
				let h = date.getHours();
				let minute = date.getMinutes();
				let second = date.getSeconds();
				minute = minute < 10 ? "0" + minute : minute;
				second = second < 10 ? "0" + second : second;
				return `${y}年${m}月${d}日 ${h}:${minute}`
			}
		},
		data() {
			return {
				list: ['代理商', '个人'],
				current: 1,
				checkboxList: [],
				productList: [],
				faultList: [],
				show: false,
				province: [], //省
				city: [], //市
				region: [], //区
				county: [], //县
				qqmapsdk: null,
				dateShow: false,
				value: Number(new Date()),
				successShow:false
			}
		},
		onHide() {


		},
		onLoad(op, tons) {
			this.qqmapsdk = new QQMapWX({
				key: '3UIBZ-WUHY3-PHT33-YXSF5-5VFHK-3BFS5'
			});
			this.getCityList()
		},
		onShow() {

			this.getproductList()
			this.getproductmodelList()
			this.getfaultList()
			//重置vuex的product数组
			if (!this.$store.state.afterSale.product.length) {
				this.$store.commit('addProduct')
			}
		},
		methods: {
			//判断数据是否为空值，为空返回true,有值为false
			isNull(data) {
				if (!data) return true;
				if (JSON.stringify(data) === '{}') return true;
				if (JSON.stringify(data) === '[]') return true;
				return false;
			},
			dateConfirm(val) {
				let timestamp = new Date().getTime()
				if (val.value <= timestamp + 3600000) {
					uni.showToast({
						title: '亲，上门取件时间只能预约在一小时后进行上门取件^_^',
						duration: 2500,
						icon: 'none'
					})
					return
				}
				let date = dateNew(val.value)
				this.$store.commit('editTime', date)
				this.dateShow = false
			},
			//获取省份数据
			getCityList() {
				let that = this
				that.qqmapsdk.getCityList({
					success: function(res) { //成功后的回调
						//console.log('省份数据：', res.result[0]); //打印省份数据
						that.province = res.result[0].map(item => ({
							value: item.id,
							text: item.fullname
						}))
					},
					fail: function(error) {
						//console.error('error111', error);
					},
					complete: function(res) {
						//console.log('res111', res);
					}
				})
			},
			//省份改变
			provinceChange(val, type) {
				if (val) {
					this.getcityId(val, type)
				}
			},
			// 传入对应省份ID获得城市数据，传入城市ID获得区县数据,依次类推
			getcityId(id, data) {
				let that = this
				that.qqmapsdk.getDistrictByCityId({
					id: id,
					success: function(res) { //成功后的回调
						that[data] = res.result[0].map(item => ({
							value: item.id,
							text: item.fullname
						}))
						console.log('对应城市ID下的区县数据：', that[data]);
					},
					fail: function(error) {
						console.log('---', error)
						that.$refs.uToast.show({
							message: '获取失败',
							type: 'error',
							icon: false
						})
					}
				})
			},
			//物流查询问题排查，寄修申请增加暂存功能，寄修详情增加删除，提交查看逻辑
			//uiui增加应用列表，设备信息页面，应用市场
			//增加产品型号
			addProduct() {
				this.$store.commit('addProduct')
			},
			changeSubsection(index) {
				console.log(index);
				this.current = index
				//客户类型 1个人 2代理商
				let type = index === 1 ? 1 : 2
				this.$store.commit('editType', type)
			},
			submitConfirm() {
				// if (!this.afterSale.express_number.trim()) return this.$refs.uToast.show({
				// 	message: '您还未将售后包裹寄出，请寄出后填写快递单号后再进行提交~',
				// 	icon: false
				// })
				this.confirm()
			},
			confirm() {
				let that = this
				that.show = false
				let addForm = JSON.parse(JSON.stringify(that.afterSale))
				addForm.express_number = addForm.express_number.trim()
				addForm.product.forEach((item, index) => {
					item.product_model_id = item.product_model_id.id
					item.product_name = item.product_name.toString()
					item.fault_name = item.fault_name.toString()
					delete item.fault_name_list
					delete item.fileList
				})
				addForm.user_province = this.province.filter(key => key.value === addForm.user_province)[0]?.text
				addForm.user_city = this.city.filter(key => key.value === addForm.user_city)[0]?.text
				addForm.user_county = this.county.filter(key => key.value === addForm.user_county)[0]?.text
				addForm.user_area = this.region.filter(key => key.value === addForm.user_area)[0]?.text
				//判断代理商是否填写地址   ---有bug
				console.log(this.afterSale.customer_type,'什么类型');
				// if(this.afterSale.customer_type == 2){
				// 	console.log('验证代理商信息');
				// 	if(addForm.user_province == '北京市' || addForm.user_province == '上海市' || addForm.user_province == '天津市' ||addForm.user_province == '重庆市'){
				// 		if(that.isNull(addForm.user_province) || that.isNull(addForm.user_city) || that.isNull(addForm.user_county) || !that.isNull(addForm.user_area)){
				// 			return that.$refs.uToast.show({
				// 				message: '代理商请填写完整地址！',
				// 				type: 'error',
				// 				icon: false
				// 			})
				// 		}
				// 	}else{
				// 		if(that.isNull(addForm.user_province) || that.isNull(addForm.user_city) || that.isNull(addForm.user_county) || that.isNull(addForm.user_area)){
				// 			return that.$refs.uToast.show({
				// 				message: '代理商请填写完整地址！',
				// 				type: 'error',
				// 				icon: false
				// 			})
				// 		}
				// 	}
				// } 
				// if(this.afterSale.as_type == 2){
				// 	if(!/^[\da-z]+$/i.test(addForm.express_number))return this.$refs.uToast.show({
				// 		message: '快递单号请勿填写无效数据类型！',
				// 		type: 'error',
				// 		icon: false
				// 	})
				// }
				console.log('confirm', addForm)
				repairAdd(addForm).then(res => {
					uni.setStorageSync('as_type', this.afterSale.as_type)
					console.log('-----', this.current)
					this.successShow = true
					setTimeout(()=>{
						this.successShow = false
						// that.$refs.uToast.show({
						// 	// message: res.msg,
						// 	icon: false,
						// 	type: 'success',
							// complete: function() {
								uni.switchTab({
									url: '/pages/index/index',
									complete: function(res) {
										that.$store.commit('clearAfterSale')
									}
								});
							// }
						// })
					},3000)
					
				}).catch(err => {
					this.$refs.uToast.show({
						message: err.msg,
						type: 'error',
						icon: false
					})
				})
			},
			//跳转售后地址
			goToUrl(url) {
				uni.navigateTo({
					url: url + '?selectAddress=confirm'
				});
			},
			getExcel() {
				this.$refs.uToast.show({
					message: '小程序暂未开发该功能',
					type: 'default',
					icon: false
				})
			},
			//获取寄回清单
			getproductList() {
				productList().then(res => {
					this.checkboxList = res.data.map(item => ({
						text: item.name,
						value: item.name
					}))
				})
			},
			//产品型号
			getproductmodelList() {
				productmodelList().then(res => {
					console.log(res.data);
					this.productList = res.data
				})
			},
			//故障类型
			getfaultList() {
				faultList().then(res => {
					this.faultList = res.data.map(item => ({
						text: item.name,
						value: item.name
					}))
					console.log('-----', this.faultList)
				})
			},
			//上传快递单号
			uploadImg() {
				let that = this
				uni.chooseImage({
					count: 1,
					success: (chooseImageRes) => {
						const tempFilePaths = chooseImageRes.tempFilePaths;
						uni.uploadFile({
							url: 'https://service.jiaoguanyi.com.cn/api/common/upload',
							filePath: tempFilePaths[0],
							name: 'file',
							header: {
								'token': that.$store.state.token
							},
							success: (res) => {
								let data = JSON.parse(res.data)
								if (data.code === 200) {
									that.$store.commit('editNumberImg', data.data.url)
									this.$refs.uToast.show({
										message: '图片上传成功',
										icon: false,
										type: 'success'
									})
								} else {
									this.$refs.uToast.show({
										message: data.msg,
										icon: false,
										type: 'error'
									})
								}
							},
							fail: (err) => {
								this.$refs.uToast.show({
									message: err.msg,
									type: 'error',
									icon: false
								})
							}
						});
					}
				});
			}
		}
	}
</script>

<style lang="scss" scoped>
	.blueBg{
		background-color: #d2e3ff;
	}
	.content {
		margin: 20rpx;
	}
	.client_type {
		position: relative;
		overflow: visible;
		.type{
			width: 60%;
			/deep/.u-subsection {
				padding: 0;
				.u-subsection__bar{
					height: 32px;
					background: #2e82ff;
				}
			}
		}
		.dateTime{
			width: 38%;
			// font-size: 
		}
		.model{
			width: 75%;
		}
		.type {
			width: 80%;
		}

		.city_input {
			width: 45%;
			/deep/.uni-select{
				border: 1px solid #2785ff !important;
			}
		}

		.address_icon {
			width: 25%;
			text-align: center;
			border-left: 1rpx solid #E6E6E6;
			margin-left: 30rpx;

			text {
				font-size: 100rpx;
			}
		}

		.address_info {
			flex: 1;

			.title {
				line-height: 40rpx;
			}
		}

		.box {
			width: 49%;
			text-align: center;
		}

		.line {
			border-right-width: 0.5px !important;
			border-color: #dadbde !important;
			border-right-style: solid;
			height: 40rpx;
		}

		.camera {
			position: absolute;
			top: 10rpx;
			right: 0;
			font-size: 60rpx;
			width: 15%;
			text-align: center;
		}

	}
	.footer_client_type{
		.box{
			width: 42%;
			padding: 40rpx 20rpx;
		}
	}

	.excel {
		text-align: center;

		text {
			font-size: 40rpx;
			margin-right: 10rpx;
			color: #19A766;
		}
	}

	.btn {
		width: 40%;
	}

	.add_icon {
		border: 1px solid;
		border-radius: 50%;
		border-color: #666;
		font-size: 14px!important;
		padding: 1px;
	}
	//弹出层后禁止滑动
	.no-scroll{
		overflow: hidden;
			position: fixed;
			width: 95%;
	}
</style>